import re
from enetity_extraction.rules import GLOBAL_RULES, Clerical_information, PERSON_RULES, ATTORNEY_RULES, \
    ATTORNEY_PERSON_RULES, COMPANY_RULES, COMPANY_PERSON_RULES, BENREN_RULES

no_need_Date=[]

def extract_detail_information_type(plaintiff_i,rule):
    plaintiff_dict = {}
    in_start_pos = plaintiff_i["start_pos"]
    if rule != COMPANY_RULES:
        for key, patterns in rule.items():
            temp_dict = {}
            for pattern in patterns:
                matches = re.finditer(pattern, plaintiff_i['match'])
                flag = 0
                for match in matches:
                    if  rule == BENREN_RULES or key=="户籍地" or key == "姓名"  or key=="身份证号":
                        flag = 1
                    if key == "姓名" and rule==PERSON_RULES:
                        flag = 2
                    if key =="出生年月日":
                        no_need_Date.append(match.group())
                    temp_dict = {
                        "paragraph_index": plaintiff_i['paragraph_index'],
                        "start_pos": in_start_pos+match.start(),
                        "end_pos": in_start_pos+match.end(),
                        "match": match.group(flag)
                    }
            plaintiff_dict[key] = temp_dict
        plaintiff_dict["all_info"]=plaintiff_i
    else:
        for key, patterns in rule.items():
            temp_dict = {}
            for pattern in patterns:
                matches = re.finditer(pattern, plaintiff_i['match'])
                flag = 0
                for match in matches:
                    if key == "企业信用代码":
                        flag = 1
                    elif key == "公司名称" or key == "地址":
                        flag = 2
                    temp_dict = {
                        "paragraph_index": plaintiff_i['paragraph_index'],
                        "start_pos": in_start_pos + match.start(),
                        "end_pos": in_start_pos + match.end(),
                        "match": match.group(flag)
                    }
            plaintiff_dict[key] = temp_dict
        if '代表人' in plaintiff_i.keys():
            plaintiff_dict2={}
            for key2, patterns2 in COMPANY_PERSON_RULES.items():
                temp_dict = {}
                for pattern in patterns2:
                    matches = re.finditer(pattern, plaintiff_i['代表人']['match'])
                    flag = 0
                    for match in matches:
                        if key2 == "姓名":
                            flag = 2
                        temp_dict = {
                            "paragraph_index": plaintiff_i['paragraph_index'],
                            "start_pos": plaintiff_i['代表人']['start_pos'] + match.start(),
                            "end_pos": plaintiff_i['代表人']['start_pos'] + match.end(),
                            "match": match.group(flag)
                        }
                plaintiff_dict2[key2] = temp_dict
            plaintiff_dict['代表人']=plaintiff_dict2
        plaintiff_dict["all_info"] = plaintiff_i
    return plaintiff_dict

def extract_detail_information(extracted_info, info_name):
    plaintiff = extracted_info[info_name]
    for i in range(len(plaintiff)):
        if info_name == "委托诉讼代理人信息" :
            if "律师" in plaintiff[i]['match']:
                plaintiff[i] = extract_detail_information_type(plaintiff[i],ATTORNEY_RULES)
            else:
                plaintiff[i] = extract_detail_information_type(plaintiff[i],ATTORNEY_PERSON_RULES)
        else:
            if "公司" in plaintiff[i]['match'] or "代码" in plaintiff[i]['match']:
                plaintiff[i] = extract_detail_information_type(plaintiff[i], COMPANY_RULES)
            elif "本人" in plaintiff[i]['match']:
                plaintiff[i] = extract_detail_information_type(plaintiff[i], BENREN_RULES)
            else:
                plaintiff[i] = extract_detail_information_type(plaintiff[i], PERSON_RULES)
    extracted_info[info_name]=plaintiff
    return extracted_info

def extract_money(data):
    filtered_data = []

    for item in data:
        should_add = True
        for other_item in data:
            if item['paragraph_index'] == other_item['paragraph_index'] and item['end_pos'] == other_item['end_pos']:
                if item['start_pos'] > other_item['start_pos']:
                    should_add = False
                    break
        if should_add:
            filtered_data.append(item)
    return filtered_data
    # print(filtered_data)ccc
def people_data_check(extract_info_list):
    people_data = []
    for extract in extract_info_list:
        if '出生年月日' in extract:
            people_data.append(extract['出生年月日'])
        else:
            continue
    return people_data

def extract_sequence_number(data):
    for item in data:
        item['match'] = re.sub(r'[;：:；。]', '', item['match'])
    return data

def extract_information(text):

    paragraph_length=[]
    for item in text:
        paragraph_length.append(len(item)+1)

    extracted_info = {} #创建一个字典，用于存储提取到的信息
    for key, patterns in GLOBAL_RULES.items():
        temp_result = []
        for pattern in patterns:
            total_length = 0
            for paragraph_index, paragraph in enumerate(text):
                if paragraph_index!=0:
                    total_length += paragraph_length[paragraph_index-1]
                matches=re.finditer(pattern, paragraph)
                for match in matches:
                    temp_dict={
                        "paragraph_index": paragraph_index,
                        "start_pos": total_length + match.start(),
                        "end_pos": total_length + match.end(),
                        "match": match.group()
                    }
                    if key == "审判时间":
                        no_need_Date.append(match.group())
                    if (key == "原告信息" or key == "被告信息") and "公司" in match.group() and (paragraph_index+1)<len(text) and "代表人" in text[paragraph_index+1]:
                        temp_dict["代表人"]={
                        "paragraph_index": paragraph_index,
                        "start_pos": total_length + paragraph_length[paragraph_index],
                        "end_pos": total_length + paragraph_length[paragraph_index]+len(text[paragraph_index+1]),
                        "match": text[paragraph_index+1]
                    }
                    if temp_dict not in temp_result:
                        temp_result.append(temp_dict)
        if  key == "原告信息" or key == "被告信息" or key == "委托诉讼代理人信息" or key == "第三人" or key=="法院名称" or key=="本人" or key=="上诉人" or key=="被上诉人" or key=='尾部落款信息':
            extracted_info[key] = temp_result
        elif key=="金额":
            extracted_info[key] = extract_money(temp_result)
        elif key == "正文序号":
            extracted_info[key] = extract_sequence_number(temp_result)
        elif temp_result:
            extracted_info[key] = temp_result[0] if len(temp_result) == 1 else temp_result
        else:
            extracted_info[key] = {}

    # 案号内部信息处理
    if bool(extracted_info['案号']):
        case = extracted_info['案号']['match']
        in_start_pos=extracted_info['案号']["start_pos"]
        case_section = {}
        for key, pattern in Clerical_information.items():
            case_section[key] = []
            matches = re.finditer(pattern, case)
            flag=0
            temp_dict = {}
            for match in matches:
                if key=="收案年度":
                    flag=1
                temp_dict = {
                    "paragraph_index": extracted_info['案号']['paragraph_index'],
                    "start_pos": in_start_pos+match.start(),
                    "end_pos": in_start_pos+match.end(),
                    "match": match.group(flag)
                }
            extracted_info[key] = temp_dict
    else:
        extracted_info['收案年度'] = {}
        extracted_info['法院代字'] = {}
        extracted_info['类型代字'] = {}
        extracted_info['案件编号'] = {}
    people_data_list = []
    if len(extracted_info['原告信息'])!=0:
        extracted_info=extract_detail_information(extracted_info=extracted_info, info_name='原告信息')
        people_data_list += people_data_check(extract_info_list=extracted_info)
    if len(extracted_info['被告信息']) != 0:
        extracted_info=extract_detail_information(extracted_info=extracted_info, info_name='被告信息')
        people_data_list += people_data_check(extract_info_list=extracted_info)
    if len(extracted_info['上诉人']) != 0:
        extracted_info = extract_detail_information(extracted_info=extracted_info, info_name='上诉人')
        people_data_list += people_data_check(extract_info_list=extracted_info)
    if len(extracted_info['被上诉人']) != 0:
        extracted_info = extract_detail_information(extracted_info=extracted_info, info_name='被上诉人')
        people_data_list += people_data_check(extract_info_list=extracted_info)
    if len(extracted_info['委托诉讼代理人信息']) != 0:
        extracted_info=extract_detail_information(extracted_info=extracted_info, info_name='委托诉讼代理人信息')
    if len(extracted_info['第三人'])!=0:
        extracted_info = extract_detail_information(extracted_info=extracted_info, info_name='第三人')
    if len(extracted_info['本人'])!=0:
        extracted_info = extract_detail_information(extracted_info=extracted_info, info_name='本人')

    mid_date = []
    total_length = 0
    pattern = r"\d{4}年\d{1,2}月\d{1,2}日"
    for paragraph_index, paragraph in enumerate(text):
        if paragraph_index != 0:
            total_length += paragraph_length[paragraph_index - 1]
        matches = re.finditer(pattern, paragraph)
        for match in matches:
            if match.group() in no_need_Date:
                continue
            temp_dict = {
                "paragraph_index": paragraph_index,
                "start_pos": total_length + match.start(),
                "end_pos": total_length + match.end(),
                "match": match.group()
            }
            mid_date.append(temp_dict)
    unique_dicts = set(tuple(sorted(d.items())) for d in mid_date+people_data_list)
    result = [dict(item) for item in unique_dicts]
    extracted_info['中间日期'] = result

    # mid_date = []
    # total_length = 0
    # for paragraph_index, paragraph in enumerate(text):
    #     if paragraph_index != 0:
    #         total_length += paragraph_length[paragraph_index - 1]
    #     if "诉讼请求：" in paragraph:
    #         pattern=r"\d{4}年\d{1,2}月\d{1,2}日"
    #         matches = re.finditer(pattern, paragraph)
    #         for match in matches:
    #             if match.group() in no_need_Date:
    #                 continue
    #             temp_dict = {
    #                 "paragraph_index": paragraph_index,
    #                 "start_pos": total_length+match.start(),
    #                 "end_pos": total_length+match.end(),
    #                 "match": match.group()
    #             }
    #             mid_date.append(temp_dict)
    # extracted_info['中间日期']=mid_date

    return extracted_info

